package com.free.semantic.core.common.serializeimpl;

import com.alibaba.fastjson.JSONObject;
import com.free.semantic.core.RelationFunction;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SerializeFunctionGroup implements ApplicationContextAware {

    private static Map<String, BaseSerializeImpl> functionMap;

    public RelationFunction getFunctionByTYpe(String type, JSONObject str) {
        if (functionMap.containsKey(type)) {
            return functionMap.get(type).fromParam(str);
        }
        throw new RuntimeException(String.format("不存在 %s的关系", str));
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        Map<String, BaseSerializeImpl> beansOfType = context.getBeansOfType(BaseSerializeImpl.class);
        functionMap = beansOfType.values().stream().collect(Collectors
                .toMap(BaseSerializeImpl::getImplType, Function.identity()));
    }

}
